package com.token.utils;

import java.nio.charset.StandardCharsets;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import lombok.extern.slf4j.Slf4j;

/**
 * @auther: henriy
 * @Date: 2023/12/5
 */
@Slf4j
public class Base64Util {

    /**
     * 加密秘钥，长度只能是16位，24位，32位
     */
    private static final byte[] KEYS = "1qaz2wsx3edc1234".getBytes(StandardCharsets.UTF_8);

    /**
     * 加密
     *
     * @param encryptContent 需加密内容
     * @return
     */
    public static String encryptBase64(String encryptContent) {
        try {
            byte[] byteKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), KEYS).getEncoded();
            SymmetricCrypto aes = SecureUtil.aes(byteKey);
            // 加密
            return aes.encryptBase64(encryptContent);
        } catch (Exception e) {
            log.error("加密异常:{}", e.getMessage());
        }

        return null;
    }

    /**
     * 解密
     *
     * @param encryptString 需解密内容
     * @return
     */
    public static String decryptBase64(String encryptString) {
        try {
            byte[] byteKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), KEYS).getEncoded();
            SymmetricCrypto aes = SecureUtil.aes(byteKey);
            // 解密
            return aes.decryptStr(encryptString);
        } catch (Exception e) {
            log.error("解密异常:{}", e.getMessage());
        }

        return null;
    }

    public static void main(String[] args) {
        String a = "123456";
        String b = encryptBase64(a);
        System.out.println(b);
        System.out.println(encryptBase64(a));
        System.out.println(decryptBase64(b));
    }
}

